/* Copyright (c) 2016-2020 Enfry Ltd. All Rights Reserved.
 * 
 * This software is the confidential and proprietary information of Enfry. 
 * You shall not disclose such Confidential Information
 * and shall use it only in accordance with the terms of the agreements
 * you entered into with Enfry.
 */
package com.enfry.storage.interceptor;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.enfry.storage.interceptor.IProcessor;
import com.enfry.storage.Response;
import com.enfry.storage.exception.ExCode;
import com.enfry.storage.interceptor.FileSizeLimitProcessor;

/**
 * 文件大小限制。
 * @Title com.enfry.storage.interceptor.FileSizeLimitProcessor
 * @author liulei
 * @date 2016年7月25日
 */
public class FileSizeLimitProcessor implements IProcessor {
    private static Logger logger = LoggerFactory.getLogger(FileSizeLimitProcessor.class);
    private long totalMaxSize;    // 所有文件最大容量，单位：KB
    private long singleMaxSize;   // 单个文件最大容量，单位：KB

    public void setTotalMaxSize(long totalMaxSize) {
        this.totalMaxSize = totalMaxSize;
    }

    public void setSingleMaxSize(long singleMaxSize) {
        this.singleMaxSize = singleMaxSize;
    }

    @Override
    public boolean process(HttpServletRequest request, HttpServletResponse response, Object handler, String reqApiName) throws IOException {
        long toltalSize = 0;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Iterator<Entry<String, MultipartFile>> iterator = multipartRequest.getFileMap().entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, MultipartFile> entry = iterator.next();
            MultipartFile file = entry.getValue();
            long size = file.getSize()/1000;
            if(size > singleMaxSize) {
                Response rep = new Response(ExCode.FILE_UPLOAD_SINGLE_MAX_SIZE);
                logger.debug(rep.toString());
                response.getWriter().write(rep.toString());
                return false;
            }
            toltalSize += size;
        }
        
        logger.debug("允许上传最大容量(KB)：" + totalMaxSize + "，实际文件总大小(KB)：" + toltalSize);
        
        if(toltalSize > totalMaxSize) {
            Response rep = new Response(ExCode.FILE_UPLOAD_TOTAL_MAX_SIZE);
            logger.debug(rep.toString());
            response.getWriter().write(rep.toString());
            return false;
        }
        return true;
    }
}
